<!--
 * @PageName: @忘记密码
 * @Description: 
 * @FilePath: /glm-mes-pc/src/views/forgotPassword.vue
-->
<template>
	<div class="forgot">
		<!-- 手机号获取验证码表单 -->
		<el-form ref="phoneRef" :model="phoneForm" :rules="phoneRules" class="phone-form" v-if="!showPassword">
			<div class="title"><img src="@/assets/images/sidbar_logo.png" alt="" /></div>
			<!-- 手机号 -->
			<el-form-item prop="phone" class="mb36">
				<span style="color: #fff; font-size: 16px">手机号：{{ phoneNumber }}</span>
				<!-- <el-input v-model="phoneForm.phone" size="large" auto-complete="off" placeholder="请输入手机号" @input="codeInput('phone')">
					<template #prefix>
						<svg-icon icon-class="shouji" class="el-input__icon input-icon" />
					</template>
				</el-input> -->
			</el-form-item>

			<el-form-item prop="code" class="mb36">
				<el-input v-model="phoneForm.code" size="large" auto-complete="off" placeholder="请输入验证码" @input="codeInput('code')">
					<template #prefix>
						<svg-icon icon-class="yanzhengma" class="el-input__icon input-icon" />
					</template>
					<template #append>
						<el-button @click="onShow" :loading="sendCodeLoading" :disabled="disabled" style="width: 120px">
							<span>{{ sendCodeContent }}</span>
						</el-button>
					</template>
				</el-input>
			</el-form-item>

			<!-- 确定按钮 -->
			<el-form-item>
				<el-button :loading="loading" size="large" type="primary" class="w100 submit-btn" @click.prevent="save">确 定</el-button>
			</el-form-item>
		</el-form>

		<!-- 密码重置表单 -->
		<el-form ref="forgotRef" :model="forgotForm" :rules="forgotRules" class="phone-form" v-else>
			<div class="title"><img src="@/assets/images/login_title.png" alt="" /></div>
			<!-- 新密码 -->
			<el-form-item prop="password" class="mb36">
				<el-input v-model="forgotForm.password" type="password" size="large" auto-complete="off" placeholder="请输入新密码" show-password ref="psdRef">
					<template #prefix><svg-icon icon-class="psd" class="el-input__icon input-icon psd" /></template>
				</el-input>
			</el-form-item>
			<!-- 确认新密码 -->
			<el-form-item prop="secondPassword" class="mb36">
				<el-input v-model="forgotForm.secondPassword" type="password" size="large" auto-complete="off" placeholder="请确认新密码" show-password @keyup.enter="handleSubmitPwd">
					<template #prefix><svg-icon icon-class="psd" class="el-input__icon input-icon psd" /></template>
				</el-input>
			</el-form-item>

			<!-- 提交按钮 -->
			<el-form-item>
				<el-button :loading="submitLoading" size="large" type="primary" @click.prevent="handleSubmitPwd" class="submit-btn w100">
					<span v-if="!submitLoading">提 交</span>
					<span v-else>提 交 中...</span>
				</el-button>
			</el-form-item>
		</el-form>

		<Vcode :show="isShow" @success="onSuccess" @close="onClose" />
	</div>
	<!-- 备案号 -->
	<Icp />
</template>

<script setup>
import Icp from '@/components/Icp/index.vue'
import { ref } from 'vue'
import { ElMessageBox } from 'element-plus'
import useUserStore from '@/store/modules/user'
import Vcode from 'vue3-puzzle-vcode'
import { getCaptchaAPI, checkCaptchaAPI, updatePasswordAPI } from '@/api/login'
const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()
console.log('window.history.state===>', window.history.state)
const account = window.history.state.account
const phoneNumber = window.history.state.phoneNumber
const phoneForm = ref({
	phone: '',
	code: ''
})
const phoneRules = {
	// phone: [
	// 	{ required: true, message: '请输入手机号', trigger: 'blur' },
	// 	{ pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
	// ],
	code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}
const sendCodeContent = ref('发送验证码')
const loading = ref(false)
const sendCodeLoading = ref(false)
const isShow = ref(false)
const disabled = ref(false)
const showPassword = ref(false)

// 点击发送验证码显示拼图校验
const onShow = () => {
	isShow.value = true
}
const onClose = () => {
	isShow.value = false
}
const onSuccess = () => {
	onClose() // 验证成功，需要手动关闭模态框
	sendCode()
}

const sendCode = async () => {
	sendCodeLoading.value = true
	getCaptchaAPI({
		account
	})
		.then((res) => {
			proxy.$modal.msgSuccess(res.msg)
			sendCodeLoading.value = false
			disabled.value = true
			startCountdown()
		})
		.catch((err) => {
			sendCodeLoading.value = false
		})
}
// 60s倒计时
const startCountdown = () => {
	let seconds = 60
	const timer = setInterval(function () {
		seconds--
		if (seconds > 0) {
			sendCodeContent.value = `发送验证码(${seconds})`
		} else {
			clearInterval(timer)
			sendCodeContent.value = '发送验证码'
			disabled.value = false
		}
	}, 1000)
}
// 正则校验剔除掉非数字，并且限制长度为6或者11
const codeInput = (type) => {
	phoneForm.value.code = phoneForm.value.code.replace(/\D/g, '')
	if (phoneForm.value.code.length > 6 && type === 'code') {
		phoneForm.value.code = phoneForm.value.code.slice(0, 6)
	}
	if (phoneForm.value.phone.length > 11 && type === 'phone') {
		phoneForm.value.phone = phoneForm.value.phone.slice(0, 11)
	}
}
const save = () => {
	proxy.$refs.phoneRef.validate((valid) => {
		if (!valid) return false
		loading.value = true
		checkCaptchaAPI({
			account,
			code: phoneForm.value.code
		})
			.then((res) => {
				proxy.$modal.msgSuccess(res.msg)
				loading.value = false
				showPassword.value = true
			})
			.catch((err) => {
				loading.value = false
			})
	})
}

const forgotForm = ref({
	password: '', // 第一次密码
	secondPassword: '' // 第二次密码
})
const submitLoading = ref(false)
// 两次密码是否一致的校验函数
const equalToPassword = (rule, value, callback) => {
	if (forgotForm.value.password !== value) {
		callback(new Error('两次输入的密码不一致'))
	} else {
		callback()
	}
}
// 密码验证规则
const forgotRules = {
	password: [
		{ required: true, trigger: 'blur', message: '请输入新密码' },
		{ pattern: /^[a-zA-Z0-9!@#$%^&*]+$/, message: '密码只能输入数字，字母，特殊符号', trigger: 'blur' },
		{ min: 6, max: 20, message: '用户密码长度必须介于 6 和 20 之间', trigger: 'blur' }
	],
	secondPassword: [
		{ required: true, trigger: 'blur', message: '请确认新密码' },
		{ min: 6, max: 20, message: '用户密码长度必须介于 6 和 20 之间', trigger: 'blur' },
		{ pattern: /^[a-zA-Z0-9!@#$%^&*]+$/, message: '密码只能输入数字，字母，特殊符号', trigger: 'blur' },
		{ required: true, validator: equalToPassword, trigger: 'blur' }
	]
}

// 提交新密码
function handleSubmitPwd() {
	proxy.$refs.forgotRef.validate((valid) => {
		if (valid) {
			submitLoading.value = true
			const data = {
				// phoneNumber: phoneForm.value.phone,
				account,
				code: phoneForm.value.code,
				password: forgotForm.value.password
			}
			updatePasswordAPI(data)
				.then(() => {
					submitLoading.value = false
					router.push({ path: '/login' })
					// ElMessageBox.alert('修改密码成功!', '提示', {
					// 	confirmButtonText: '确定',
					// 	type: 'success',
					// 	'show-close': false
					// }).then(() => {
					// 	// 点击确定按钮直接登录
					// 	useUserStore()
					// 		.login({ username: data.userName, password: data.password })
					// 		.then(() => {
					// 			router.push({ path: '/' })
					// 		})
					// })
				})
				.catch(() => {
					submitLoading.value = false
				})
		}
	})
}
</script>

<style lang="scss" scoped>
.forgot {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	height: 100%;
	background-image: url('https://glm-1324073348.cos.ap-nanjing.myqcloud.com/2024/10/18/fa076049315040fd86a62760486af3071729231799530.png');
	background-size: 100% 100%;
	.phone-form {
		border-radius: 6px;
		background: #ffffff;
		width: 400px;
		padding: 25px 25px 5px 25px;
		background-color: transparent;
		.psd-container {
			display: flex;
			align-items: center;
			margin-bottom: 14px;
			justify-content: space-between;
			.forgot-psd {
				font-size: 14px;
				color: #fff;
				cursor: pointer;
			}
		}
		.title {
			display: flex;
			justify-content: center;
			margin-bottom: 40px;
		}
		.el-input {
			height: 40px;
			background-color: transparent;
			input {
				height: 40px;
			}
		}
		.input-icon {
			height: 40px;
			width: 16px;
			margin-left: 0px;
			color: #fff;
		}
	}
}
// 输入框文字
:deep(.el-input__inner) {
	color: #fff !important;
}
// 输入框背景色
:deep(.el-input__wrapper) {
	background-color: rgb(255, 255, 255, 0.01);
}
// 输入框的placeholder
:deep(.el-input__inner::placeholder) {
	color: #fff;
}
:deep(.el-button, .el-button:hover) {
	border: 0 !important;
}
</style>
